<?php
namespace plugin\ky_shouyin\app\controller;

use support\Request;
use support\Db;

class CashierController extends BaseController
{
    /**
     * 收银台首页
     */
    public function index()
    {
        return $this->view('cashier/index');
    }
    
    /**
     * 获取商品列表
     */
    public function getGoods(Request $request)
    {
        $keyword = $request->get('keyword', '');
        $query = Db::table('ky_goods')->where('status', 1);
        
        if ($keyword) {
            $query->where(function ($query) use ($keyword) {
                $query->where('name', 'like', "%{$keyword}%")
                    ->orWhere('code', 'like', "%{$keyword}%");
            });
        }
        
        $goods = $query->get();
        return json(['code' => 0, 'msg' => 'ok', 'data' => $goods]);
    }
    
    /**
     * 获取会员信息
     */
    public function getMember(Request $request)
    {
        $keyword = $request->get('keyword');
        if (!$keyword) {
            return json(['code' => 1, 'msg' => '请输入会员卡号或手机号']);
        }

        $member = Db::table('ky_member')
            ->where('card_no', $keyword)
            ->orWhere('phone', $keyword)
            ->first();

        if (!$member) {
            return json(['code' => 1, 'msg' => '未找到会员信息']);
        }

        return json(['code' => 0, 'msg' => 'ok', 'data' => $member]);
    }
    
    /**
     * 创建会员
     */
    public function createMember(Request $request)
    {
        if ($request->method() !== 'POST') {
            return json(['code' => 1, 'msg' => '无效的请求']);
        }

        $phone = $request->post('phone');
        $exists = Db::table('ky_member')->where('phone', $phone)->exists();
        if ($exists) {
            return json(['code' => 1, 'msg' => '该手机号已被使用']);
        }

        $data = [
            'name' => $request->post('name'),
            'phone' => $phone,
            'card_no' => date('YmdHis') . rand(1000, 9999),
            'balance' => 0,
            'points' => 0,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ];

        $id = Db::table('ky_member')->insertGetId($data);
        if (!$id) {
            return json(['code' => 1, 'msg' => '开卡失败']);
        }

        return json(['code' => 0, 'msg' => '开卡成功']);
    }
    
    /**
     * 会员充值
     */
    public function recharge(Request $request)
    {
        if ($request->method() !== 'POST') {
            return json(['code' => 1, 'msg' => '无效的请求']);
        }

        $memberId = $request->post('member_id');
        $amount = $request->post('amount');

        if ($amount <= 0) {
            return json(['code' => 1, 'msg' => '充值金额必须大于0']);
        }

        try {
            Db::beginTransaction();

            $member = Db::table('ky_member')->where('id', $memberId)->lockForUpdate()->first();
            if (!$member) {
                throw new \Exception('会员不存在');
            }

            // 更新会员余额
            Db::table('ky_member')
                ->where('id', $memberId)
                ->update([
                    'balance' => $member->balance + $amount,
                    'updated_at' => date('Y-m-d H:i:s')
                ]);

            Db::commit();
            return json(['code' => 0, 'msg' => '充值成功']);
        } catch (\Exception $e) {
            Db::rollBack();
            return json(['code' => 1, 'msg' => '充值失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 创建订单
     */
    public function createOrder(Request $request)
    {
        if ($request->method() != 'POST') {
            return json(['code' => 1, 'msg' => '非法请求']);
        }
        
        $data = $request->post();
        
        if (empty($data['items'])) {
            return json(['code' => 1, 'msg' => '请选择商品']);
        }
        
        try {
            Db::beginTransaction();
            
            // 创建订单
            $orderId = Db::table('ky_order')->insertGetId([
                'order_no' => date('YmdHis') . rand(1000, 9999),
                'member_id' => $data['member_id'] ?? 0,
                'total_amount' => $data['total_amount'],
                'discount_amount' => $data['discount_amount'],
                'actual_amount' => $data['actual_amount'],
                'payment_method' => $data['payment_method'],
                'status' => 1,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            
            // 创建订单商品
            foreach ($data['items'] as $item) {
                Db::table('ky_order_goods')->insert([
                    'order_id' => $orderId,
                    'goods_id' => $item['id'],
                    'goods_name' => $item['name'],
                    'goods_price' => $item['price'],
                    'quantity' => $item['quantity'],
                    'total_amount' => $item['price'] * $item['quantity'],
                    'created_at' => date('Y-m-d H:i:s')
                ]);
                
                // 更新商品库存
                Db::table('ky_goods')
                    ->where('id', $item['id'])
                    ->decrement('stock', $item['quantity']);
            }
            
            // 如果是会员，扣除余额并记录积分
            if (!empty($data['member_id'])) {
                if ($data['payment_method'] == 'balance') {
                    Db::table('ky_member')
                        ->where('id', $data['member_id'])
                        ->decrement('balance', $data['actual_amount']);
                }
                
                // 累计积分 (按实付金额1:1累计)
                Db::table('ky_member')
                    ->where('id', $data['member_id'])
                    ->increment('points', floor($data['actual_amount']));
            }
            
            Db::commit();
            return json(['code' => 0, 'msg' => '结算成功']);
        } catch (\Exception $e) {
            Db::rollBack();
            return json(['code' => 1, 'msg' => '结算失败：' . $e->getMessage()]);
        }
    }
} 